package org.yidu.novel.security;

import java.util.Collections;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.yidu.novel.repository.TUserRepository;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private TUserRepository userRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/*", "/css/**", "/js/**", "/images/**", "/cover/**", "/webjars/**").permitAll().antMatchers("/user/**")
                .hasAnyAuthority("USER", "ADMIN").antMatchers("/ADMIN/**").hasAuthority("admin").anyRequest().authenticated().and().formLogin()
                .loginPage("/login").permitAll().and().logout().permitAll().deleteCookies("JSESSIONID").invalidateHttpSession(true).permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(loginId -> {
            return new User("test00", "test00", Collections.singleton(new SimpleGrantedAuthority("USER")));
            // List<TUser> userList =
            // userRepository.findByLoginId(loginId);
            // if (!CollectionUtils.isEmpty(userList)) {
            // return new User(userList.get(0).getUserName(),
            // userList.get(0).getPassword(), Collections.singleton(new
            // SimpleGrantedAuthority("USER")));
            // } else {
            // throw new UsernameNotFoundException("Invalid username");
            // }
        });
    }
}
